

from django import http
from django.shortcuts import render
from django_redis import get_redis_connection
# Create your views here.
from django.views import View

from apps.verifications.constant import SMS_CODE_EXPRIE_TIME, YUNTONGXUN_EXPRIE_TIME
from libs.captcha.captcha import captcha
from random import randint

from libs.yuntongxun.sms import CCP
from utils.response_code import RETCODE
from redis import StrictRedis
import logging
logger = logging.getLogger('django')


class ImageCodeView(View):
    def get(self,request,uuid):
        # 生成图片验证码
        text,image = captcha.generate_captcha()
        # 保存图片验证码
        redis_conn = get_redis_connection('code')

        redis_conn.setex('img_%s'% uuid,120,text)
        return http.HttpResponse(image,content_type='image/jpeg')

class SMSCodeView(View):
    # 步骤
    def get(self,request,mobile):
        params = request.GET
    # 1.后端要接收数据
        uuid = params.get('image_code_id')
        redis_cli = params.get('image_code')
    # 生成图片验证码
        text,image = captcha.generate_captcha()
    # 2.验证数据　对比　用户提交的uuid与redis数据库中的是否一致
        try:
            # 2.1 连接redis
            redis_conn = get_redis_connection('code')
            # 2.2 根据uuid获取redis中的数据
            redis_server = redis_conn.get('img_%s' % uuid)
            # 验证标记位是否存在
            sms_flag = redis_conn.get('sms_flag_%s'% mobile)
            if sms_flag is not None:
                return http.HttpResponseBadRequest('操作太频繁了')
            # 2.3 验证图形验证码是否过期
            if redis_server is None:
                return http.HttpResponseBadRequest("图形验证码已失效")
            # 2.4 比对
            if redis_server.decode().lower() != redis_cli.lower():
                return http.HttpResponseBadRequest("图形验证码不一致")
            # 删除图形验证码，防止恶意测试
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseBadRequest('数据库连接问题')
    # 3.生成短信验证码
        sms_code = "%06d" % randint(0,999999)
        # 输出短信验证码
        logger.info(sms_code)
    # 4.保存短信验证码
    #     redis_conn.setex("sms_%s"%mobile,SMS_CODE_EXPRIE_TIME,sms_code)
        # 设置标记位
        # redis_conn.setex("sms_flag_%s"%mobile,60,1)
        # 通过连接redis 创建管道实例
        pl = redis_conn.pipeline()
        # 将redis指令缓存到管道中
        pl.setex("sms_%s"%mobile,SMS_CODE_EXPRIE_TIME,sms_code)
        pl.setex("sms_flag_%s"%mobile,60,1)
        # 通过excute来执行管道
        pl.execute()
    # 5.发送短信验证码
    #     CCP().send_template_sms(mobile,[sms_code,YUNTONGXUN_EXPRIE_TIME],1)
        # 改为celery
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)
    # 6.返回响应

        return http.JsonResponse({"code":RETCODE.OK})